## This function makes various maps

library(rgdal)
library(gridExtra)
library(dplyr)
library(sp)
library(rgeos)
library(fields)
library(readr)
library(ggmap)
library(maptools)


## Read in precinct shape file
prec2016shp <- readOGR(dsn = "../shapes/SBE_PRECINCTS_20161004", layer = "Precincts")
## and border identifiers
bf2016 <- read_delim(file = "border_precincts.csv", delim = "\t", col_names = TRUE)

## Read in county shape file
countyshp <- readOGR(dsn = "../shapes/CountyBoundary", layer = "CountyBoundary")
midpoints <- coordinates(countyshp)
## Read in changes to early voting laws
polls <- read_delim(file = "2012-2016_Early_Voting_Changes.csv", delim = "\t", col_names = TRUE)
polls[is.na(polls)] <- 0
## change county to uppercase 
polls <- polls %>%  mutate(county = toupper(county),
                           offhours2012 = evehours2012 + sathours2012 + sunhours2012,
                           offhours2016 = evehours2016 + sathours2016 + sunhours2016,
                           offhoursDiff = offhours2016 - offhours2012,
                           offhoursChg = (offhoursDiff / offhours2012) * 100)


## Merge in poll details into the shape file (using old merge command since left_join seems not to like shapefiles)
countyshp <- merge(x = countyshp, y = polls, by.x = "NAME", by.y = "county")

###### Make map of Sampson - Duplin, illustrating border idea

pdf (file = "../plots/sampson-duplin-example.pdf", height = 5, width = 5)

sampson2use <- filter(bf2016, COUNTY_NAM == "SAMPSON", DUPLIN == TRUE)
duplin2use <- filter(bf2016, COUNTY_NAM == "DUPLIN", SAMPSON == TRUE)
row2use_sampson = match("SAMPSON", countyshp$NAME)
row2use_duplin = match("DUPLIN", countyshp$NAME)

plot (countyshp[c(row2use_sampson, row2use_duplin),], add = FALSE , col = "grey90")
plot (prec2016shp[prec2016shp$ENR_DESC %in% sampson2use$ENR_DESC,], col = "grey50", add = TRUE)
plot (prec2016shp[prec2016shp$ENR_DESC %in% duplin2use$ENR_DESC,], col = "grey50", add = TRUE)

border2use = gIntersection(countyshp[row2use_sampson,], countyshp[row2use_duplin,])
plot(border2use, add = TRUE, col= "black", lwd = 5)
text (x = midpoints[row2use_sampson, 1], 
      y = midpoints[row2use_sampson, 2], "Sampson", col = "black", cex = 1)

text (x = midpoints[row2use_duplin, 1], 
      y = midpoints[row2use_duplin, 2], "Duplin", col = "black", cex = 1)

dev.off()

# MAKE MAPS OF INSTITUTIONAL CHANGES #

# get the data ready -- reread the shape file, fortify and merge poll info
# very important to merge poll info AFTER fortify...
countyshp <- readOGR(dsn = "../shapes/CountyBoundary", layer = "CountyBoundary")
countyshp <- fortify(countyshp, region = "NAME") 
countyshp <- merge(x = countyshp, y = polls, by.x = "id", by.y = "county")

# get ready to strip the ggplot2 default axes, but keep the legend
ditch_the_axes <- theme(
  axis.text = element_blank(),
  axis.line = element_blank(),
  axis.ticks = element_blank(),
  panel.border = element_blank(),
  panel.grid = element_blank()
)

# greyscale
col2use<- grey.colors(50, start = 1, end = 0)

## plot total hours
# even legend breaks
breaks <- round(seq(from = min(countyshp$totalhoursChg),
                    to = max(countyshp$totalhoursChg),
                    by = ((max(countyshp$totalhoursChg)-min(countyshp$totalhoursChg))*.25)),
                digits = 1)

totalhours <- ggplot(data = countyshp, mapping = aes(x = long, y = lat, group = group)) + 
  coord_fixed(1.3) + 
  geom_polygon(data = countyshp, aes(fill = totalhoursChg)) +
  geom_polygon(color = "black", fill = NA) + 
  scale_fill_gradientn(colours=col2use,
                       limits = c(min(countyshp$totalhoursChg),
                                  max(countyshp$totalhoursChg)),
                       breaks = breaks, 
                       labels=paste(as.character(breaks), "%", sep = ""))+
  theme_bw() +
  theme(legend.title = element_blank(),
        legend.position="bottom")+
  theme(legend.key.width = unit(1.25, "cm"))+
  theme(legend.key.height = unit(.25, "cm"))+
  ditch_the_axes+
  labs(x ="Total hours", y = " ")
  
## plot evening hours
# even legend breaks
breaks <- round(seq(from = min(countyshp$evehoursChg),
                    to = max(countyshp$evehoursChg),
                    by = ((max(countyshp$evehoursChg)-min(countyshp$evehoursChg))*.25)),
                digits = 1)

evehours <- ggplot(data = countyshp, mapping = aes(x = long, y = lat, group = group)) + 
  coord_fixed(1.3) + 
  geom_polygon(data = countyshp, aes(fill = evehoursChg)) +
  geom_polygon(color = "black", fill = NA) + 
  scale_fill_gradientn(colours=col2use,
                       limits = c(min(countyshp$evehoursChg),
                                  max(countyshp$evehoursChg)),
                       breaks = breaks, 
                       labels=paste(as.character(breaks), "%", sep = ""))+
  theme_bw() +
  theme(legend.title = element_blank(),
        legend.position="bottom")+
  theme(legend.key.width = unit(1.25, "cm"))+
  theme(legend.key.height = unit(.25, "cm"))+
  ditch_the_axes+
  labs(x ="Evening Hours", y = " ")



## plot saturday hours
# even legend breaks
breaks <- round(seq(from = min(countyshp$sathoursChg),
                    to = max(countyshp$sathoursChg),
                    by = ((max(countyshp$sathoursChg)-min(countyshp$sathoursChg))*.25)),
                digits = 1)

sathours <- ggplot(data = countyshp, mapping = aes(x = long, y = lat, group = group)) + 
  coord_fixed(1.3) + 
  geom_polygon(data = countyshp, aes(fill = sathoursChg)) +
  geom_polygon(color = "black", fill = NA) + 
  scale_fill_gradientn(colours=col2use,
                       limits = c(min(countyshp$sathoursChg),
                                  max(countyshp$sathoursChg)),
                       breaks = breaks, 
                       labels=paste(as.character(breaks), "%", sep = ""))+
  theme_bw() +
  theme(legend.title = element_blank(),
        legend.position="bottom")+
  theme(legend.key.width = unit(1.25, "cm"))+
  theme(legend.key.height = unit(.25, "cm"))+
  ditch_the_axes+
  labs(x ="Saturday hours", y = " ")

## plot sunday hours
# even legend breaks
breaks <- round(seq(from = min(countyshp$sunhoursChg),
                    to = max(countyshp$sunhoursChg),
                    by = ((max(countyshp$sunhoursChg)-min(countyshp$sunhoursChg))*.25)),
                digits = 1)

sunhours <- ggplot(data = countyshp, mapping = aes(x = long, y = lat, group = group)) + 
  coord_fixed(1.3) + 
  geom_polygon(data = countyshp, aes(fill = sunhoursChg)) +
  geom_polygon(color = "black", fill = NA) + 
  scale_fill_gradientn(colours=col2use,
                       limits = c(min(countyshp$sunhoursChg),
                                  max(countyshp$sunhoursChg)),
                       breaks = breaks, 
                       labels=paste(as.character(breaks), "%", sep = ""))+
  theme_bw() +
  theme(legend.title = element_blank(),
        legend.position="bottom")+
  theme(legend.key.width = unit(1.25, "cm"))+
  theme(legend.key.height = unit(.25, "cm"))+
  ditch_the_axes+
  labs(x ="Sunday hours", y = " ")


## plot site changes
# even legend breaks
breaks <- round(seq(from = min(countyshp$sitesChg),
                    to = max(countyshp$sitesChg),
                    by = ((max(countyshp$sitesChg)-min(countyshp$sitesChg))*.25)),
                digits = 1)

sites <- ggplot(data = countyshp, mapping = aes(x = long, y = lat, group = group)) + 
  coord_fixed(1.3) + 
  geom_polygon(data = countyshp, aes(fill = sitesChg)) +
  geom_polygon(color = "black", fill = NA) + 
  scale_fill_gradientn(colours=col2use,
                       limits = c(min(countyshp$sitesChg),
                                  max(countyshp$sitesChg)),
                       breaks = breaks, 
                       labels=paste(as.character(breaks), "%", sep = ""))+
  theme_bw() +
  theme(legend.title = element_blank(),
        legend.position="bottom")+
  theme(legend.key.width = unit(1.25, "cm"))+
  theme(legend.key.height = unit(.25, "cm"))+
  ditch_the_axes+
  labs(x ="Sites", y = " ")



# put the plots on one grid
all_maps <- grid.arrange(totalhours, evehours, sathours, sunhours, sites, 
                         ncol = 2, nrow = 3)

ggsave (all_maps, filename = paste("all_maps_grid",".pdf", sep = ""),
        width = 7, height = 7)

